package com.common.exception;

import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 路亚
 * @version 0.1
 * @className JavaGatewayException
 * @description
 * @date 2024/12/11 15:26
 * @since jdk11
 */
@Component
public class JavaGatewayException implements ErrorWebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        if (ex instanceof JavaSmException) {
            JavaSmException exception = (JavaSmException) ex;
            ServerHttpResponse response = exchange.getResponse();
            response.getHeaders().add("Content-Type", "application/json; charset=utf-8");

            // 构建包含code和message的响应体
            String msg = String.format("{\"code\": %d, \"message\": \"%s\"}", exception.getCodeAndMsg().getCode(), exception.getCodeAndMsg().getMsg());
            DataBuffer buffer = response.bufferFactory().wrap(msg.getBytes());
            return response.writeWith(Mono.just(buffer));
        }
        // 可以添加更多的异常类型处理
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        return response.setComplete();
    }
}
